<template>
   <div class="rule">
    <SearchBar @onSearch="handleSearch"  @childFn="resetFormSearch">
      <SearchBarItem label="商户名称：" :labelLg="8">
        <Input type="text" v-model="searchModule.merchantName" placeholder="请输入商户名称" clearable />
      </SearchBarItem>
      <SearchBarItem label="产品名称：" :labelLg="8">
        <Input type="text" v-model="searchModule.productName" placeholder="请输入产品名称" clearable />
      </SearchBarItem>
      <SearchBarItem label="规则名称：" :labelLg="8">
        <Input type="text" v-model="searchModule.ruleName" placeholder="请输入规则名称" clearable />
      </SearchBarItem>
      <SearchBarItem label="规则编码：" :labelLg="8">
        <Input type="text" v-model="searchModule.ruleCode" placeholder="请输入规则编码" clearable />
      </SearchBarItem>
      <SearchBarItem label="规则有效时间：" :labelLg="8">
        <DatePicker type="daterange" class="searchDate" ref="createDatePicker" :value="searchModule.dataTime" split-panels placeholder="请选择" @on-change="searchTime"></DatePicker>
      </SearchBarItem>
      <SearchBarItem label="结算类型：" :labelLg="8">
        <Select v-model="searchModule.settlementType" placeholder="请选择" :clearable="isClear">
          <Option :value="item.key" v-for="(item, key) in seleteSettlementType" :key="key">{{item.value}}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="清分规则：" :labelLg="8">
        <Select v-model="searchModule.clearingRule" placeholder="请选择" :clearable="isClear">
          <Option :value="item.key" v-for="(item, key) in seleteSettlementRule" :key="key">{{item.value}}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="规则类型：" :labelLg="8">
        <Select v-model="searchModule.ruleType" placeholder="请选择" :clearable="isClear">
          <Option :value="item.key" v-for="(item, key) in seleteRuleType" :key="key">{{item.value}}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="规则状态：" :labelLg="8">
        <Select v-model="searchModule.settlementStatus" placeholder="请选择" :clearable="isClear">
          <Option :value="item.key" v-for="(item, key) in seleteSettlementStatus" :key="key">{{item.value}}</Option>
        </Select>
      </SearchBarItem>
    </SearchBar>
    <RemoteTable :namespace="namespace" :columns="columns" @onSortChange="onSortChange">

      <template #extra>
        <Authc permissions="trade:merchant:rule:edit">
          <Button type="primary" @click="handleClick('add', 'searchModule')">新增</Button>
        </Authc>
        <Authc permissions="trade:merchant:rule:export">
          <Button type="primary" @click="exportExcel">导出</Button>
        </Authc>
      </template>
    </RemoteTable>

    <!-- 编辑弹窗 -->
    <Modal v-model="isShow" :visible.sync="isShow" :title="title" width='800' class="ruleModal">
      <Loading :loading="false">
        <Form ref="dataModule" :label-width="130" :model="dataModule" :rules="ruleValidate">

          <FormItem label="规则类型" prop="ruleType">
            <RadioGroup v-model="dataModule.ruleType" @on-change="handleTypeGadio">
              <Radio v-for="item in seleteRuleType" :key="item.value" :label="item.key">{{item.value}}</Radio>
            </RadioGroup>
        </FormItem>

          <FormItem label="所属商户" prop="merchantCode">
            <Select v-model="dataModule.merchantCode" :label-in-value="true" filterable placeholder="请选择" @on-change="bindleMCode">
              <Option v-for="item in merchantNameSelect" :key="item.value" :value="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>

          <FormItem label="所属产品" prop="productCode" v-if="dataModule.merchantCode">
            <Select v-model="dataModule.productCode" :label-in-value="true" filterable placeholder="请选择" @on-change="bindleProductCode">
              <Option v-for="(item, index) in productNameSelect" :key="index" :value="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>

          <FormItem label="产品编码" v-if="dataModule.productCode">
            <div>{{ dataModule.productCode }}</div>
          </FormItem>

          <FormItem prop="ruleName" label="规则名称">
            <Input type="text" v-model="dataModule.ruleName" placeholder="请填写,字数不超过32" maxlength="32"/>
          </FormItem>

          <FormItem label="结算类型" prop="settlementType">
            <Select v-model="dataModule.settlementType" placeholder="请选择" @on-change="handleCloseType">
              <Option v-for="(item, index) in seleteSettlementType" :key="item + index" :value="item.key">{{ item.value }}</Option>
            </Select>
          </FormItem>

          <FormItem label="产品单价" prop="productPrice" v-if="dataModule.ruleType == '1'">
            <Input type="text" v-model.number="dataModule.productPrice" maxlength="10" placeholder="请填写"/>
          </FormItem>

          <Row>
            <Col span="11">
              <FormItem label="清分周期类型" prop="clearingCycleMode">
                <Radio-group v-model="dataModule.clearingCycleMode">
                    <Radio label="0">天</Radio>
                    <Radio label="1">月</Radio>
                </Radio-group>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="清分日期" v-if="dataModule.clearingCycleMode == '0'">
                <span>{{ dataModule.clearingCycleValue }} 日清分</span>
              </FormItem>
              <FormItem label="清分日期" v-if="dataModule.clearingCycleMode == '1'">
                <span>{{ dataModule.clearingCycleValueExt }}日/{{ dataModule.clearingCycleValue }}个月 </span>
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="11">
              <FormItem prop="clearingCycleValue" label="清分周期值">
                <InputNumber  type="text" v-model.number="dataModule.clearingCycleValue" :max="12" :min="1" placeholder="请填写月份"/>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem prop="clearingCycleValueExt" label="清分周期拓展值" v-if="dataModule.clearingCycleMode == '1'">
                <InputNumber type="text" v-model.number="dataModule.clearingCycleValueExt" :max="31" :min="1" placeholder="请填写日期"/>
              </FormItem>
            </Col>
          </Row>
          {{ closeTypeDataType }}

          <div v-if="typeRadioDataType">
            <!-- 产品 -->
            <FormItem label="清分规则" prop="clearingRule" :rules="{required: closeTypeDataType,validator: validateSequence}">
              <Radio-group v-model="dataModule.clearingRule" v-if="closeTypeDataType" @on-change="handleRuleType">
                <Radio v-for="item in seleteSettlementRule" :key="item.value" :label="item.key">{{item.value}}</Radio>
              </Radio-group>
              <div v-else>百分比</div>
            </FormItem>

            <Row v-if="dataModule.clearingRule == 1 && dataModule.settlementType == 1">
              <Col span="12">
                <FormItem label="平台应收" prop="platformReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                  <Input type="text" v-model.number="dataModule.platformReceivable" placeholder="请填写">
                    <span slot="append">%</span>
                  </Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收" prop="merchantReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                  <Input type="text" v-model.number="dataModule.merchantReceivable" placeholder="请填写">
                    <span slot="append">%</span>
                  </Input>
                </FormItem>
              </Col>
            </Row>

            <Row v-if="dataModule.clearingRule == 2 && dataModule.settlementType == 1">
              <Col span="12">
                <FormItem label="平台应收" prop="platformReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                  <Input type="text" v-model.number="dataModule.platformReceivable" placeholder="请填写">
                    <span slot="append">元</span>
                  </Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收" prop="merchantReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                  <Input type="text" v-model.number="dataModule.merchantReceivable" placeholder="请填写">
                    <span slot="append">元</span>
                  </Input>
                </FormItem>
              </Col>
            </Row>

            <Row v-if="dataModule.settlementType == 2 || dataModule.settlementType == 3">
              <Col span="12">
                <FormItem label="平台应收11" prop="platformReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                  <div>100%</div>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收11" prop="merchantReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                  <div>0%</div>
                </FormItem>
              </Col>
            </Row>

            <div class="offlineSettleRule" v-if="dataModule.settlementType == 3">
              <FormItem label="线下结算规则" :prop="lineCloseTypeDataType ? 'lineClearingRule' : ''">
                <Radio-group v-model="dataModule.lineClearingRule">
                  <Radio v-for="item in seleteSettlementRule" :key="item.value" :label="item.key">{{item.value}}</Radio>
                </Radio-group>
              </FormItem>
              <Row v-if="dataModule.lineClearingRule == 1">
                <Col span="12">
                  <FormItem label="平台应收" prop="linePlatformReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                    <Input type="text" v-model.number="dataModule.linePlatformReceivable" placeholder="请填写">
                      <span slot="append">%</span>
                    </Input>
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="商户应收" prop="lineMerchantReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                    <Input type="text" v-model.number="dataModule.lineMerchantReceivable" placeholder="请填写">
                      <span slot="append">%</span>
                    </Input>
                  </FormItem>
                </Col>
              </Row>

              <Row v-if="dataModule.lineClearingRule == 2">
                <Col span="12">
                  <FormItem label="平台应收" prop="linePlatformReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                    <Input type="text" v-model.number="dataModule.linePlatformReceivable" placeholder="请填写">
                      <span slot="append">元</span>
                    </Input>
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="商户应收" prop="lineMerchantReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                    <Input type="text" v-model.number="dataModule.lineMerchantReceivable" placeholder="请填写">
                      <span slot="append">元</span>
                    </Input>
                  </FormItem>
                </Col>
              </Row>

            </div>

          </div>

          <div v-else>
            <!-- 通用 -->
            <FormItem label="清分规则" prop="clearingRule" :rules="{required: closeTypeDataType && typeRadioDataType}">
              <div>百分比</div>
            </FormItem>

            <Row v-if="dataModule.settlementType == 1">
              <Col span="12">
                <FormItem label="平台应收" prop="platformReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                  <Input type="text" v-model.number="dataModule.platformReceivable" placeholder="请填写">
                    <span slot="append">%</span>
                  </Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收" prop="merchantReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                  <Input type="text" v-model.number="dataModule.merchantReceivable" placeholder="请填写">
                    <span slot="append">%</span>
                  </Input>
                </FormItem>
              </Col>
            </Row>

            <Row v-if="dataModule.settlementType == 2 || dataModule.settlementType == 3">
              <Col span="12">
                <FormItem label="平台应收" prop="platformReceivable">
                  <div>100%</div>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="商户应收" prop="merchantReceivable">
                  <div>0%</div>
                </FormItem>
              </Col>
            </Row>

            <div class="offlineSettleRule" v-if="dataModule.settlementType == 3">
              <FormItem label="线下结算规则" :prop="lineCloseTypeDataType ? 'lineClearingRule' : ''">
                <Radio-group v-model="dataModule.lineClearingRule">
                  <Radio v-for="item in seleteSettlementRule" :key="item.value" :label="item.key">{{item.value}}</Radio>
                </Radio-group>
              </FormItem>

              <Row v-if="dataModule.lineClearingRule == 1">
                <Col span="12">
                  <FormItem label="平台应收" prop="linePlatformReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                    <Input type="text" v-model.number="dataModule.linePlatformReceivable" placeholder="请填写">
                      <span slot="append">%</span>
                    </Input>
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="商户应收" prop="lineMerchantReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                    <Input type="text" v-model.number="dataModule.lineMerchantReceivable" placeholder="请填写">
                      <span slot="append">%</span>
                    </Input>
                  </FormItem>
                </Col>
              </Row>

              <Row v-if="dataModule.lineClearingRule == 2">
                <Col span="12">
                  <FormItem label="平台应收" prop="linePlatformReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                    <Input type="text" v-model.number="dataModule.linePlatformReceivable" placeholder="请填写">
                      <span slot="append">元</span>
                    </Input>
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="商户应收" prop="lineMerchantReceivable" :rules="{required: closeTypeDataType,validator: validateSequence}">
                    <Input type="text" v-model.number="dataModule.lineMerchantReceivable" placeholder="请填写">
                      <span slot="append">元</span>
                    </Input>
                  </FormItem>
                </Col>
              </Row>

            </div>

          </div>

          <FormItem label="有效时间" prop="validTime">
            <DatePicker v-model="dataModule.validTime" format="yyyy-MM-dd" type="daterange" placeholder="请选择" @on-change="setDateRange" @on-clear="handleClear" clearable></DatePicker>
          </FormItem>
          <!-- <FormItem label="有效时间" prop="validTime">
            <DatePicker :value='[dataModule.effectiveDate, dataModule.expireDate]' format="yyyy-MM-dd" type="daterange" placeholder="请选择" @on-change="setDateRange" @on-clear="handleClear" clearable></DatePicker>
          </FormItem> -->

          <FormItem label="优先级" prop="priorityLevel">
            <Input type="text" v-model.trim="dataModule.priorityLevel" maxlength="4" placeholder="请填写"/>
          </FormItem>
        </Form>
      </Loading>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitCancel('dataModule')">取消</Button>
        <Button type="primary" @click="handleSubmit('dataModule')">确定</Button>
      </div>
    </Modal>

    <!-- 详情弹窗 -->
    <Modal v-model="isShowDetele" :visible.sync="isShowDetele" :title="dataModuleDetele.ruleName" width='800' class="ruleDeteleModal" :footer-hide="true">
      <Loading :loading="false">
        <Form ref="dataModuleDetele" :label-width="130" :model="dataModuleDetele">

          <div class="controlNo">规则编号：{{dataModuleDetele.ruleType}}</div>

          <h3 class="ruleDeteleTitle">产品信息</h3>

          <FormItem label="所属商户">
            <span>{{dataModuleDetele.merchantName}}</span>
          </FormItem>

          <FormItem label="商户编码">
            <span>{{dataModuleDetele.merchantCode}}</span>
          </FormItem>

          <FormItem label="所属产品">
            <span>{{dataModuleDetele.productName}}</span>
          </FormItem>

          <FormItem label="产品编码">
            <span>{{dataModuleDetele.productCode}}</span>
          </FormItem>

          <h3 class="ruleDeteleTitle">规则信息</h3>

          <FormItem label="规则名称">
            <span>{{dataModuleDetele.ruleName}}</span>
          </FormItem>

          <Row>
            <Col span="11">
              <FormItem label="规则类型">
                <span>{{dataModuleDetele.ruleTypeCn}}</span>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="结算类型">
                <span>{{dataModuleDetele.settlementTypeCn}}</span>
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="11">
              <FormItem label="产品单价" v-if="dataModuleDetele.ruleType === '1'">
                <span>￥ {{ dataModuleDetele.productPrice }}</span>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="清分规则">
                <span>{{dataModuleDetele.productPrice}}</span>
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="11">
              <FormItem label="平台应收">
                <span>￥ {{dataModuleDetele.platformReceivable}}</span>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="商户应收">
                <span>￥ {{dataModuleDetele.merchantReceivable}}</span>
              </FormItem>
            </Col>
          </Row>

          <FormItem label="清分日期">
            <span>{{ dataModuleDetele.clearingCycleValue }}日/ {{ dataModuleDetele.clearingCycleValueExt }}个月</span>
          </FormItem>

           <Row>
            <Col span="11">
              <FormItem label="清分周期值">
                <span>{{dataModuleDetele.clearingCycleValue}}</span>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="清分周期拓展值" v-if="dataModuleDetele.clearingCycleMode != 0">
                <span>{{dataModuleDetele.clearingCycleValueExt}}</span>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="清分周期类型">
                <span>{{dataModuleDetele.clearingCycleMode == 0 ? '按天' : '按月'}}</span>
              </FormItem>
            </Col>
          </Row>

          <FormItem label="有效时间">
            <span>{{dataModuleDetele.effectiveDate}} ~ {{dataModuleDetele.expireDate}}</span>
          </FormItem>

          <FormItem label="优先级">
            <span>{{dataModuleDetele.priorityLevel}}</span>
          </FormItem>
        </Form>
      </Loading>
    </Modal>

  </div>
</template>

<script>
import {
  Button,
  Input,
  InputNumber,
  Modal,
  Message,
  Col,
  Row,
  Form,
  FormItem,
  DatePicker,
  Select,
  Option,
  Card,
  Radio,
  RadioGroup
} from "view-design";
import Loading from "@/components/Loading";
import RemoteTable from "@/components/RemoteTable";
import RemoteSelect from "@/components/RemoteSelect";
import SearchBar from "@/components/SearchBar";
import { namespace } from "../module/rule";
import Authc from "@/components/Authc";
import Action from "./Action";
import config from "@/utils/config";
import appService from "@/utils/appService";

export default {
  name: "tables_page",
  components: {
    Loading,
    RemoteTable,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    RemoteSelect,
    Authc,
    Action,
    Button,
    Input,
    InputNumber,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card,
    Radio,
    RadioGroup
  },
  data() {
    return {
      title: "",
      isShow: false,
      isShowDetele: false,
      namespace: namespace,
      loading: true,
      isClear: true,
      dataModule: {
        ruleType:'1',
        effectiveDate: '',
        expireDate: ''
      },
      dataModuleDetele: {},
      searchModule: {
        // effectiveDate: '',
        // expireDate: ''
      },
      ruleValidate: {
        ruleType: [{ required: true, message: '请选择', trigger: 'change' }],
        merchantCode: [{ required: true, message: '请选择', trigger: 'change' }],
        productCode: [{ required: true,  message: '请选择', trigger: 'change' }],
        ruleName: [{ required: true, message: '请填写', trigger: 'blur' }],
        productPrice: [{ required: true, validator: this.validateSequence, trigger: "blur" }],
        settlementType: [{ required: true, message: '请选择', trigger: 'change' }],
        clearingCycleMode: [{ required: true, message: '请选择', trigger: 'change' }],
        clearingCycleValue: [{ required: true, validator: this.validateSequence, trigger: "change" }],
        clearingCycleValueExt: [{ required: true, validator: this.validateSequence, trigger: "change" }],

        // clearingRule: [{ required: true, message: '请选择', trigger: 'change' }],
        // platformReceivable: [{ required: true, validator: this.validateSequence, trigger: "blur" }],
        // merchantReceivable: [{ required: true, validator: this.validateSequence, trigger: "blur" }],

        lineClearingRule: [{ required: true, message: '请选择', trigger: 'change' }],
        linePlatformReceivable: [{ required: true, validator: this.validateSequence, trigger: "blur" }],
        lineMerchantReceivable: [{ required: true, validator: this.validateSequence, trigger: "blur" }],

        validTime: [{ required: true, validator: this.validateDaterange, trigger: "change" }],
        priorityLevel: [{ required: true, validator: this.validateSequence, trigger: "blur" }]
      },
      productNameSelect: [], // 产品
      merchantNameSelect: [], // 商户
      columns: [
        {
          title: "序号",
          type: "index",
          width: 80,
          align: "center",
          fixed: "left"
        },
        {
          title: "规则编码",
          key: "id",
          minWidth: 150,
          align: "center",
          fixed: "left"
        },
        {
          title: "优先级",
          key: "priorityLevel",
          minWidth: 150,
          align: "center"
        },
        {
          title: "商户名称",
          key: "merchantName",
          minWidth: 150,
          align: "center"
        },
        {
          title: "产品名称",
          key: "productName",
          minWidth: 150,
          align: "center"
        },
        {
          title: "规则类型",
          key: "ruleTypeCn",
          minWidth: 150,
          align: "center"
        },
        {
          title: "规则名称",
          key: "ruleName",
          minWidth: 150,
          align: "center"
        },
        {
          title: "结算类型",
          key: "settlementTypeCn",
          minWidth: 150,
          align: "center"
        },
        {
          title: "清分规则",
          key: "clearingRuleCn",
          minWidth: 150,
          align: "center"
        },
        {
          title: "状态",
          key: "settlementStatusCn",
          minWidth: 150,
          align: "center"
        },
        {
          title: "规则生效时间",
          key: "effectiveDate",
          minWidth: 150,
          align: "center"
        },
        {
          title: "规则失效时间",
          key: "expireDate",
          minWidth: 150,
          align: "center"
        },
        {
          title: "操作",
          key: "action",
          width: 150,
          fixed: "right",
          align: "center",
          permissions: ["trade:merchant:rule"],
          render: function(h, data) {
            return h(Action, {
              props: {
                row: data.row
              }
            });
          }
        }
      ],
      seleteSettlementType: [], // 结算类型
      seleteSettlementRule: [], // 清分规则
      seleteRuleType: [], // 规则类型
      seleteSettlementStatus: [], //规则状态
      closeTypeDataType: true, // 自定义结算类型状态
      typeRadioDataType: true,  // 自定义规则状态
      lineCloseTypeDataType: true, // 自定义线下结算类型状态
    };
  },
  created() {
    /** 如果 url 没有带参数，就重置请求参数 **/
    this.$store.commit(`${namespace}/reviseQuery`);
    this.getMerchantSearchKey();
  },
  methods: {
    /** 导出 */
    async exportExcel () {
      try {
        let res = await this.$store.dispatch(`${namespace}/exportExcel`, this.searchModule);
          let link = document.createElement('a');
          // 创建Blob对象，设置文件类型
          let blob = new Blob([res.data], {type: "application/vnd.ms-excel"})
          let objectUrl = URL.createObjectURL(blob) // 创建URL
          link.href = objectUrl
          link.download = '清分规则.xlsx' // 自定义文件名
          link.click() // 下载文件
          URL.revokeObjectURL(objectUrl); // 释放内存
      } catch (error) {
        this.$Message.error({
          content: '导出失败'
        })
      }
    },
    /** 表单验证 **/
    validateSequence(rule, value, callback){
      if (value === '') {
            callback(new Error('请输入'));
      } else if (!Number.isInteger(+value)) {
            callback(new Error('输入数字'));
      } else {
            callback();
      }
    },
    /** 表单 日期验证 **/
    validateDaterange(rule, value, callback){
      if (!value) {
        callback(new Error("日期不能为空"))
      } else {
          callback()
      }
    },
    // 清空事件；
    resetFormSearch() {
      this.$set(this.searchModule, 'merchantName', '');  //商户名称
      this.$set(this.searchModule, 'productName', '');   //产品名称
      this.$set(this.searchModule, 'ruleName', '');      //规则名称
      this.$set(this.searchModule, 'ruleCode', '');      //规则编码
      this.$set(this.searchModule, 'settlementType', '');  //结算类型
      this.$set(this.searchModule, 'clearingRule', '');  //清分规则
      this.$set(this.searchModule, 'ruleType', '');  //规则类型
      this.$set(this.searchModule, 'settlementStatus', ''); //规则状态
      // 清空时间选择
      this.$refs["createDatePicker"].handleClear();
    },
    // 商户
    getMerchant () {
      let page = {
        currentPage: 1,
        pageSize: 9999
      }
      this.$store.dispatch(`${namespace}/getMerchant`, page).then((res)=>{
        if (res.data.errorCode === 0) {
          let data = res.data.data.list.map(({ merchantName, merchantCode }) => {
            return {
              label: merchantName ? merchantName : '',
              value: merchantCode ? merchantCode : ''
            }
          })
          this.merchantNameSelect = data;
        }
      })
    },
    // 商品
    getProduct (data) {
      let page = {
        currentPage: 1,
        pageSize: 9999,
        merchantCode: data
      }
      this.$store.dispatch(`${namespace}/getProduct`, page).then((res)=>{
        if (res.data.errorCode === 0) {
          let data = res.data.data.list.map(({ productName, productCode }) => {
            return {
              label: productName ? productName : '',
              value: productCode ? productCode : ''
            }
          })
          this.productNameSelect = data;
        }
      })
    },
    // 字典
    getMerchantSearchKey () {
      this.$store.dispatch(`${namespace}/getMerchantSearchKey`).then((res)=>{
        if (res.data.errorCode === 0) {
          let data = res.data.data;
          this.seleteRuleType = data.settlementCycleMode; // 规则类型
          this.seleteSettlementType = data.settlementType; // 结算类型
          this.seleteSettlementRule = data.settlementClearRule; // 清分规则
          this.seleteSettlementStatus = data.settlementStatus; // 状态
        }
      })
    },
    // 所属产品
    bindleProductCode (val) {
      this.dataModule.productName = val ? val.label : '';
    },

    // 所属商户
    bindleMCode (val) {
      this.dataModule.merchantName = val ? val.label : '';
      console.log(val, '333333333333333')
      this.getProduct(val.value);
    },

    // 编辑有效时间
    setDateRange (val) {
      this.dataModule.validTime = val
      this.dataModule.effectiveDate = val[0]
      this.dataModule.expireDate = val[1]
    },
    handleClear () {
      this.$set(this.dataModule, 'validTime', [])
    },

    // 搜索时间
    searchTime (date, type) {
      console.log(date)
      console.log(type)
      this.searchModule.effectiveDate = date ? date[0] : ''
      this.searchModule.expireDate = date ? date[1] : ''
    },

    // 结算类型
    handleCloseType (val) {
      console.log(val);
      if (!this.dataModule.ruleType) {
        this.$refs.dataModule.validateField('ruleType');
      } else {
        if (this.typeRadioDataType) {
          // 产品规则
          if (val == '1') {
            console.log('清分')
            this.closeTypeDataType = true;
            this.lineCloseTypeDataType = false;
          } else if(val == '2'){
            console.log('结算')
            this.closeTypeDataType = false;
            this.lineCloseTypeDataType = false;
            this.$set(this.dataModule, 'platformReceivable', '100');
            this.$set(this.dataModule, 'merchantReceivable', '0');
            console.log(this.dataModule.platformReceivable);
            console.log(this.dataModule.merchantReceivable);
          }else {
            console.log('平台')
            this.closeTypeDataType = false;
            this.lineCloseTypeDataType = true;
            this.$set(this.dataModule, 'lineClearingRule', '1')
            this.$set(this.dataModule, 'platformReceivable', '100');
            this.$set(this.dataModule, 'merchantReceivable', '0');
          }
        } else if (!this.typeRadioDataType) {
          // 通用规则
            if (val == '1') {
              console.log('清分')
              this.closeTypeDataType = true
              this.lineCloseTypeDataType = false;
              this.dataModule.clearingRule = 1;
              this.dataModule.platformReceivable = '';
              this.dataModule.merchantReceivable = '';
              this.resetFormRule()
            } else if(val == '2'){
              console.log('结算')
              this.closeTypeDataType = false;
              this.lineCloseTypeDataType = false;
              this.dataModule.clearingRule = 1;
              this.$set(this.dataModule, 'platformReceivable', '100');
              this.$set(this.dataModule, 'merchantReceivable', '0');
            }else {
              console.log('平台');
              this.closeTypeDataType = false;
              this.lineCloseTypeDataType = true;
              this.$set(this.dataModule, 'clearingRule', 1);
              this.$set(this.dataModule, 'lineClearingRule', '1');
              this.$set(this.dataModule, 'platformReceivable', '100');
              this.$set(this.dataModule, 'merchantReceivable', '0');
            }
        }
      }
    },
    // 规则类型
    handleTypeGadio (val) {
      if (val === '1') {
        this.typeRadioDataType = true;
      } else {
        this.typeRadioDataType = false;
      }
      this.dataModule = {};
      this.closeTypeDataType = true;
      this.$set(this.dataModule, 'ruleType', val);
      this.$set(this.dataModule, 'settlementType', '1');
      this.$set(this.dataModule, 'clearingRule', '1');
      this.resetFormSettlement();
    },

    handleSubmitCancel(formName) {
      this.isShow = false;
      this.$refs[formName].resetFields();
    },

    handleSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$store.dispatch(`${namespace}/save`, this.dataModule).then(e => {
            if( e.errorCode === 0 ){
                this.$Message.success(e.msg);
                this.isShow = false;
                this.$store.dispatch(`${namespace}/query`);
              }
          });
        } else {
          if (!this.typeRadioDataType) {
            this.resetFormRule()
          }
          console.log("error submit!!");
          return false;
        }
      });
    },

    handleClick(type) {
      switch (type) {
        case "add":
        this.dataModule = {}
          this.isShow = true;
          this.title = "新增清分规则";
          this.dataModule.ruleType = '1'; /** 规则类型默认选中 */
          this.dataModule.settlementType = '1'; /** 结算类型默认选中 */
          // this.dataModule.clearingCycleMode = '0'; /** 清分周期类型默认选中 */
          // this.dataModule.clearingRule = '1'; /** 清分规则默认选中 */
          this.getMerchant();
          this.resetFormAll()
          break;
        case "edit":
          break;
        case "delete":
          break;
        default:
      }
    },
    /** 选择清分规则 **/
    handleRuleType(e){
      console.log(e);
    },
    handleSearch() {
      let page = {
        currentPage: 1,
        pageSize: 10
      }
      this.$store.dispatch(`${namespace}/query`, {...this.searchModule, ...page});
    },

    onSortChange(sort) {
      if (sort.order === "normal") {
        this.queryParam.order = [];
      } else {
        this.queryParam.order = [sort.key + " " + sort.order];
      }
      this.handleSearch();
    },
    resetFormAll () {
      this.$refs['dataModule'].resetFields()
    },

    // 结算类型
    resetFormSettlement () {
       this.$refs['dataModule'].fields.forEach(function (e) {
          if (e.prop == 'settlementType') e.resetField();
        })
    },
    resetFormRule () {
       this.$refs['dataModule'].fields.forEach(function (e) {
          if (e.prop == 'clearingRule') e.resetField();
        })
    },
    resetForm() {
       this.$refs['dataModule'].fields.forEach(function (e) {
          if (e.prop == 'platformReceivable' || e.prop == 'merchantReceivable') e.resetField();
        })
    },
    resetFormType () {
       this.$refs['dataModule'].fields.forEach(function (e) {
          if (e.prop == 'platformReceivable' || e.prop == 'merchantReceivable' || e.prop == 'settlementType') e.resetField();
        })
    }
  },
  mounted() {
    this.$bus.$on("actionType", data => {
      let id = data.id
      if (data.type === "edit") {
        this.isShowDetele = true;
        this.$store.dispatch(`${namespace}/getDetail`, id) .then(res => {
          if(res){
            this.dataModuleDetele = res.data;
          }

        });
      } else if (data.type === "delete") {
        Modal.confirm({
          render: (h, params) => {
            return h("div", [
              h(
                "div",
                {
                  class: "selfConfirm"
                },
                "作废后不可再次生效，是否确认作废?"
              )
            ]);
          },
          onOk: () => {
            return this.$store.dispatch(`${namespace}/delete`, id).then(e => {
              if( e.errorCode === 0 ){
                this.$Message.warning(e.msg);
                this.$store.dispatch(`${namespace}/query`);
              }
            });
          }
        });
      }
    });
  },
  beforeDestroy() {
      this.$bus.$off("actionType");
  },
};
</script>

<style lang="less" scoped>
.rule {
  .ruleModal {
    height: 100px;
    .introduce {
      margin: 0 10px 10px 120px;
      color: #999;
      .introduceOne {
        margin-right: 15px;
      }
    }

  }
  .searchDate{
    width: 100% !important;
  }

}
.offlineSettleRule {
  background-color: #f2f2f2;
  margin-bottom: 10px;
}
.ruleDeteleModal .ruleDeteleTitle{
      padding-bottom: 6px;
      margin-bottom: 10px;
      border-bottom: 1px solid #999;
    }
.ruleDeteleModal .ivu-form-item {
    margin-bottom: 0px;
  }
  .controlNo {
    margin-bottom: 10px;
  }
</style>
